package geowiki.data;

import java.util.ArrayList;
import java.util.List;

import processing.core.PApplet;
import processing.xml.XMLElement;

/**
 * This extracts places via YQL / Placemaker.
 */
public class YQLPlaceExtractor extends PlaceExtractor {

	public YQLPlaceExtractor(PApplet p) {
		super(p);
	}

	public List<Place> getPlaces(String content) {
		String yqlQuery = YQLQuery.getAllPlacesFromHTMLContent(content);
		return extractPlaces(yqlQuery);
	}

	public List<Place> getPlacesFromURL(String url) {
		String yqlQuery = YQLQuery.getAllPlacesFromWebpage(url);
		return extractPlaces(yqlQuery);
	}

	private List<Place> extractPlaces(String yqlQuery) {
		List<Place> places = new ArrayList<Place>();

		XMLElement xmlResponse = new XMLElement(p, yqlQuery);
		XMLElement[] placeXMLElements = xmlResponse.getChildren("results/matches/match/place");
		for (int i = 0; i < placeXMLElements.length; i++) {
			String name = placeXMLElements[i].getChild(2).getContent();
			float lat = new Float(placeXMLElements[i].getChild(3).getChild(0).getContent());
			float lng = new Float(placeXMLElements[i].getChild(3).getChild(1).getContent());

			Place place = new Place(name, lat, lng);
			places.add(place);
		}

		return places;
	}

}
